package com.glc.gao.gavin.rxjavademo.operator;

import android.view.View;

import com.glc.gao.gavin.rxjavademo.R;

import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class FlatMapActivity extends BaseActivity {
    @Override
    public int getDescribeText() {
        return R.string.describe_flat_map;
    }

    @Override
    protected int getContextView() {
        return R.layout.activity_flat_map;
    }

    public void executeFlatMap(View view) {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                print("Emitter " + 123);
                e.onNext(123);
                print("Emitter " + 345);
                e.onNext(345);
                print("Emitter " + 567);
                e.onNext(567);
                print("Emitter " + 789);
                e.onNext(789);
            }
        }).flatMap(new Function<Integer, ObservableSource<String>>() {
            @Override
            public ObservableSource<String> apply(Integer integer) throws Exception {

                ArrayList<String> strings = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    strings.add("I am value" + integer);
                }
                int delayTime = (int) (1 + Math.random() * 10);
                print("apply " + integer + " " + delayTime);
                return Observable.fromIterable(strings).delay(delayTime, TimeUnit.MICROSECONDS);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        print("accept:" + s);
                    }
                });
    }
}
